<?php

namespace App\Jobs;

use App\System\Base\Services\SmsService;
use App\System\Cis\Repositories\CisUserRepository;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;

class SendMsg implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 任务最大尝试次数。
     *
     * @var int
     */
    public $tries = 5;

    /**
     * 手机
     * @var
     */
    private $mobile;

    /**
     * 模板类型
     * @var
     */
    private $templateType;

    /**
     * 要发送的数据
     * @var
     */
    private $data;

    /**
     * 用户ID
     * @var
     */
    private $userId;
    /**
     * SendMsg constructor.
     * @param $mobile 手机号
     * @param $templateType
     * @param array $data
     * @param int $user_id 用户ID
     */
    public function __construct($mobile,$templateType, $data=[],$user_id=0)
    {
        $path = storage_path('app/public/logs/jobs.log');
        Log::useDailyFiles($path);
        Log::info('短信队列插入,用户ID为'.$user_id.'手机号'.$mobile.'模板类型：'.$templateType);

        $this->mobile = $mobile;
        $this->templateType = $templateType;
        $this->data = $data;
        $this->userId = $user_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $this->sendMsg();
    }


    public function sendMsg()
    {
        $sms = SmsService::getInstance();
        if(!$this->mobile && $this->userId)
        {//没传手机，只传了用户ID则查询手机号
            $user = CisUserRepository::getInstance();
            $user_info = $user->getUser($this->userId);
            $this->mobile = $user_info->mobile;
        }
        $path = storage_path('app/public/logs/jobs.log');
        Log::useDailyFiles($path);
        Log::info('成功执行一次队列任务:用户ID为'.$this->userId.'手机号'.$this->mobile.'模板类型：'.$this->templateType);
        if($this->mobile)
        {
            $sms->sendMsg($this->mobile,$this->templateType,$this->data);
        }

    }
}
